﻿using Candy.Infrastructure;
using Candy.Model;
using Candy.Web.Data;
using System;
using System.ServiceModel.DomainServices.Client;

namespace Candy.ViewModel
{
    public class ProjectEditViewModel : EntityEditViewModel<ProjectDto>
    {

        private bool _newProject;
        private INavigationService _navService;
        private IDataService _dataService;
        public ProjectEditViewModel(IDataService dataService, INavigationService navService, ProjectDto project, bool isNewProject)
            : base(dataService, project,  dataService.Projects)
        {
            _dataService = dataService;
            _navService = navService;
            _newProject = isNewProject;
            this.Saved += new EventHandler(ProjectEditViewModel_Saved);
            this.Canceled += ProjectEditViewModel_Canceled;
        }

        void ProjectEditViewModel_Canceled(object sender, EventArgs e)
        {
            if (_newProject)
                _navService.GoBack();
        }

        void ProjectEditViewModel_Saved(object sender, EventArgs e)
        {
            if (_newProject)
            {
                _dataService.Initialize(Entity);
                _navService.Navigate(NavigationTargets.Project);
            }
        }



        protected override void OnValidateAsync(Action<bool> callback)
        {
            base.ResetError();
            
            if (Entity.EntityState == EntityState.New || Entity.EntityState == EntityState.Detached )
            {
                _dataService.ProjectExistsAsync(Entity.Name, op =>
                    {
                        if (!op.HasError)
                        {
                            callback(!op.Value);
                        }
                        else
                        {
                            base.HandleDomainError(op, "Couldn't validate project name. Please try again.");
                        }
                    });
            }
            else
            {
                callback(true);
            }
        }
    }
}
